<?php
	require_once ("rest.inc.php");
	include_once("../backend/dataprovider.php");

	class API extends Rest{
		public function __construct(){
			parent::__construct();
		}
		
		public function processApi(){
			$func = strtolower(trim(str_replace("/", "", $_REQUEST['rquest'])));
			if((int)method_exists($this, $func) > 0){
				$this->$func();
			}else{
				$error = array('status'=>"Failed", 'message'=>"Page not found",'code'=>404);
				$this->response('', 404);
			}
		}
		
		private function login(){
			if($this->get_request_method() != "POST")
				$this->response($this->json(array('status'=>'failed','message'=>'Bad request method','code'=>406)), 406);
			
			$email = $_REQUEST["email"];
			$pwd = $_REQUEST["password"];
			
			if(!isset($email) || !isset($pwd) || empty($email) || empty($pwd)){
				$error = array('status'=>"Failed", 'message'=>"Invalid email or password",
						'code'=>400);
				$this->response($this->json($error), 400);
				return;
			}
			
			$salt = "U" . $pwd . "P";
			$h_pass = sha1($salt);
				
			$sql = "select _username from Users where _username='{$email}' and hex(_password)='{$h_pass}' and _active=1";
			$userlst = DataProvider::executeQuery($sql);
			if($userlst != false){
				if($row = mysql_fetch_array($userlst, MYSQL_ASSOC)){
					session_start();
					$_SESSION["logedUser"] = $row["_username"];
					$error = array('status'=>"Success", 'message'=>"OK", 'code'=>200);
					$this->response($this->json($error), 200);
				}
			}
			
			$error = array('status'=>"Failed", 'message'=>"Invalid email or password",
					'code'=>400);
			$this->response($this->json($error), 400);
		}//end login
		
		private function logout(){
			$error = array('status'=>"Success", 'message'=>"OK",
					'code'=>200);
			$this->response($this->json($error), 200);
		}
		
		//Encode array into JSON
		private function json($data){
			if(is_array($data))
				return json_encode($data);
		}
	}//end class
	
	$api = new API();
	$api->processApi();
?>